<template>
  <div class="p-2 page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="执行总裁" prop="proPresidentId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="proLeaderId">
              <el-select
                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                placeholder="请选择项目负责人" style="width: 240px" clearable @click="showSearchLeaderSelector = true"
                @clear="clearSearchLeader">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchLeaderSelector = true"> 选择项目负责人 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="备份人员" prop="backupBy">
              <el-select
                :model-value="selectedSearchBackupPerson ? selectedSearchBackupPerson.userName || selectedSearchBackupPerson.nickName : ''"
                placeholder="请选择备份人员" style="width: 240px" clearable @click="showSearchBackupPersonSelector = true"
                @clear="clearSearchBackupPerson">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchBackupPersonSelector = true"> 选择备份人员 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="queryParams.dataType" placeholder="请选择数据类型" clearable style="width: 240px">
                <el-option v-for="dict in pro_data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="备份时间" prop="backupTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['project:proDataBackup:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['project:proDataBackup:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['project:proDataBackup:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['project:proDataBackup:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="proDataBackupList" @selection-change="handleSelectionChange" border class="flex-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="备份人员" align="center" prop="backupName" />
        <el-table-column label="备份日期" align="center" prop="backupTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.backupTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="proName" :show-overflow-tooltip="true" />
        <el-table-column label="数据类型" align="center" prop="dataType">
          <template #default="scope">
            <dict-tag :options="pro_data_type" :value="scope.row.dataType" />
          </template>
        </el-table-column>
        <el-table-column label="资料名称" align="center" prop="dataName" :show-overflow-tooltip="true" />
        <el-table-column label="审核状态" align="center" width="120" prop="auditStatus">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.auditStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                v-hasPermi="['project:proDataBackup:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['project:proDataBackup:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['project:proDataBackup:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="提交审核" placement="top">
              <el-button link type="success" icon="Upload" @click="handleSubmitAudit(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination class="pagination-fixed" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改数据备份记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <template #default>
        <div style="padding-right: 24px">
          <el-form ref="proDataBackupFormRef" :model="form" :rules="rules" label-width="120px" label-position="left"
            style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备份人员" prop="backupBy">
                  <el-input v-model="backupPersonName" placeholder="系统当前用户" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备份日期" prop="backupTime">
                  <el-date-picker clearable v-model="form.backupTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择备份日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目名称" prop="proId">
                  <el-select v-model="form.proId" placeholder="请输入项目名称搜索" clearable filterable remote reserve-keyword
                    :remote-method="searchProjects" :loading="projectLoading" style="width: 100%"
                    @change="handleProjectChange">
                    <el-option v-for="project in projectList" :key="project.id"
                      :label="`${project.proName} (${project.proNumber || ''})`" :value="project.id" />
                    <template #empty>
                      <div class="text-center p-2">
                        <span v-if="projectSearchKeyword && projectList.length === 0"> 未找到相关项目 </span>
                        <span v-else> 请输入项目名称进行搜索 </span>
                      </div>
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="执行总裁" prop="proPresidentsName">
                  <el-input v-model="form.proPresidentsName" readonly placeholder="请选择项目" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目负责人" prop="proLeadersName">
                  <el-input v-model="form.proLeadersName" readonly placeholder="请选择项目" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数据类型" prop="dataType">
                  <el-select v-model="form.dataType" placeholder="请选择数据类型" style="width: 100%">
                    <el-option v-for="dict in pro_data_type" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="资料名称" prop="dataName">
                  <el-input v-model="form.dataName" placeholder="请输入资料名称" type="textarea" :rows="3"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备份路径" prop="backupPath">
                  <el-input v-model="form.backupPath" placeholder="请输入备份路径" type="textarea" :rows="3"
                    style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog :title="viewDialog.title" v-model="viewDialog.visible" width="900px" append-to-body>
      <template #default>
        <div style="padding-right: 24px">
          <el-form :model="viewForm" label-width="120px" label-position="left" style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备份人员">
                  <el-input :value="viewBackupPersonName" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备份日期">
                  <el-input :value="viewForm.backupTime" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目名称">
                  <el-input :value="viewForm.proName" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="执行总裁">
                  <el-input :value="viewForm.proPresidentsName" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目负责人">
                  <el-input :value="viewForm.proLeadersName" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备份时间">
                  <el-input :value="viewForm.backupTime" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数据类型">
                  <el-input
                    :value="pro_data_type.find(item => item.value === viewForm.dataType)?.label || viewForm.dataType"
                    readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="资料名称">
                  <el-input :value="viewForm.dataName" type="textarea" :rows="3" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备份路径">
                  <el-input :value="viewForm.backupPath" type="textarea" :rows="3" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="部门检查情况">
                  <el-input :value="viewForm.deptCheckCase" type="textarea" :rows="4" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="公司检查情况">
                  <el-input :value="viewForm.companyCheckCase" type="textarea" :rows="4" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input :value="viewForm.remark" type="textarea" :rows="4" readonly style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelView">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    

    <!-- 搜索条件用的用户选择器 -->
    <!-- 执行总裁选择器 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" title="选择执行总裁" :multiple="false"
      @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />

    <!-- 项目负责人选择器 -->
    <UserSelector v-model:visible="showSearchLeaderSelector" title="选择项目负责人" :multiple="false"
      @confirmWithIds="handleSearchLeaderConfirm" @cancel="handleSearchLeaderCancel" />

    <!-- 备份人员选择器（搜索用） -->
    <UserSelector v-model:visible="showSearchBackupPersonSelector" title="选择备份人员" :multiple="false"
      @confirmWithIds="handleSearchBackupPersonConfirm" @cancel="handleSearchBackupPersonCancel" />

    <!-- 审核流程组件 -->
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="businessType"
      :business-id="currentBackupForApproval?.id" :title="`数据备份审核-${currentBackupForApproval?.proName || ''}`"
      @confirm="handleApprovalConfirm" @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="ProDataBackup" lang="ts">
import { ProDataBackupVO, ProDataBackupQuery, ProDataBackupForm } from '@/api/project/backup/types';
import { listProDataBackup, getProDataBackup, delProDataBackup, addProDataBackup, updateProDataBackup } from '@/api/project/backup/index';
import { listProInfoForQuery } from '@/api/project/init/proInfo';
import UserSelector from '@/components/UserSelector/index.vue';
import { useUserStore } from '@/store/modules/user';
import { getToday } from '@/utils/dateUtils';
import type { DateModelType } from 'element-plus';
import ApprovalFlow from '@/components/ApprovalFlow/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 时间跨度选择器
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
// 字典数据
const { pro_data_type, approval_commit_status } = toRefs<any>(proxy?.useDict('pro_data_type', 'approval_commit_status'));

const userStore = useUserStore();

const proDataBackupList = ref<ProDataBackupVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const proDataBackupFormRef = ref<ElFormInstance>();

// 备份人员：默认当前用户
const backupPersonName = ref('');

// 搜索条件用的用户选择器相关变量
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref<any>(null);

const showSearchLeaderSelector = ref(false);
const selectedSearchLeader = ref<any>(null);

const showSearchBackupPersonSelector = ref(false);
const selectedSearchBackupPerson = ref<any>(null);

const initFormData: ProDataBackupForm = {
  id: undefined,
  proId: undefined,
  proName: '',
  proPresidentsName: '',
  proLeadersName: '',
  backupBy: undefined,
  backupTime: undefined,
  dataType: undefined,
  dataName: undefined,
  backupPath: undefined,

  remark: undefined,
}

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 查看详情对话框
const viewDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 查看详情表单数据
const viewForm = ref<ProDataBackupForm>({ ...initFormData });
const viewBackupPersonName = ref('');
const data = reactive<PageData<ProDataBackupForm, ProDataBackupQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    proName: undefined,
    proPresidentId: undefined,
    proLeaderId: undefined,
    backupBy: undefined,
    dataType: undefined,
    params: {}
  },
  rules: {
    proId: [
      { required: true, message: "项目名称不能为空", trigger: "change" }
    ],
    proPresidentsName: [
      { required: true, message: "执行总裁不能为空", trigger: "change" }
    ],
    proLeadersName: [
      { required: true, message: "项目负责人不能为空", trigger: "change" }
    ],
    backupBy: [
      {
        required: true,
        validator: (rule: any, value: any, callback: any) => {
          if (!value && !backupPersonName.value) {
            callback(new Error('备份人员不能为空'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    backupTime: [
      { required: true, message: "备份时间不能为空", trigger: "change" }
    ],
    dataType: [
      { required: true, message: "数据类型不能为空", trigger: "change" }
    ],
    dataName: [
      { required: true, message: "资料名称不能为空", trigger: "blur" }
    ],
    backupPath: [
      { required: true, message: "备份路径不能为空", trigger: "blur" }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);

// 项目搜索相关变量
const projectList = ref<any[]>([]);
const projectLoading = ref(false);
const projectSearchKeyword = ref('');

// 项目搜索函数
const searchProjects = (query: string) => {
  projectSearchKeyword.value = query;
  if (searchProjects.timer) clearTimeout(searchProjects.timer);
  searchProjects.timer = setTimeout(() => {
    getProjectList(query);
  }, 300);
};
searchProjects.timer = null;

const getProjectList = async (searchKeyword = '') => {
  try {
    projectLoading.value = true;
    const res = await listProInfoForQuery({ pageNum: 1, pageSize: 50, proName: searchKeyword || undefined, auditStatus: '3' });
    projectList.value = res.rows || [];
  } finally {
    projectLoading.value = false;
  }
};

const handleProjectChange = (proId: string | number) => {
  if (!proId) {
    form.value.proPresidentsName = '';
    form.value.proLeadersName = '';
    return;
  }
  const project = projectList.value.find((p) => p.id === proId);
  if (project) {
    form.value.proPresidentsName = project.proPresidentsName || '';
    form.value.proLeadersName = project.proLeadersName || '';
  } else {
    form.value.proPresidentsName = '';
    form.value.proLeadersName = '';
  }
};

/** 查询数据备份记录列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    // 使用addDateRange工具方法处理备份时间范围
    proxy?.addDateRange(params, dateRange.value, 'backupTime');
    const res = await listProDataBackup(params);
    proDataBackupList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 查看详情对话框取消按钮 */
const cancelView = () => {
  viewForm.value = { ...initFormData };
  viewBackupPersonName.value = '';
  viewDialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  projectList.value = [];
  projectSearchKeyword.value = '';
  backupPersonName.value = '';
  proDataBackupFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  // 清除搜索用的用户选择器状态
  selectedSearchPresident.value = null;
  selectedSearchLeader.value = null;
  selectedSearchBackupPerson.value = null;
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProDataBackupVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.backupTime = getToday();
  form.value.backupBy = userStore.userId as any;
  backupPersonName.value = userStore.name;
  dialog.visible = true;
  dialog.title = "添加数据备份记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ProDataBackupVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getProDataBackup(_id);
  Object.assign(form.value, res.data);
  // 回显备份人员名称
  backupPersonName.value = res.data.backupName || '';
  // 如果有项目ID，通过项目ID单独请求项目信息确保正确回显
  if (res.data.proId) {
    try {
      const projectRes = await listProInfoForQuery({ id: res.data.proId, pageNum: 1, pageSize: 1, auditStatus: '3' });
      if (projectRes.rows && projectRes.rows.length > 0) {
        const project = projectRes.rows[0];
        form.value.proName = project.proName;
        form.value.proPresidentsName = project.proPresidentsName || '';
        form.value.proLeadersName = project.proLeadersName || '';
        // 将项目添加到项目列表中，确保下拉框能正确显示
        projectList.value = [project];
      }
    } catch (error) {
      console.error('获取项目信息失败:', error);
      // 如果单独请求失败，尝试从通用列表中查找
      await getProjectList();
      const project = projectList.value.find(p => p.id === res.data.proId);
      if (project) {
        form.value.proName = project.proName;
        form.value.proPresidentsName = project.proPresidentsName || '';
        form.value.proLeadersName = project.proLeadersName || '';
      }
    }
  }
  dialog.visible = true;
  dialog.title = "修改数据备份记录";
}

/** 查看详情按钮操作 */
const handleView = async (row: ProDataBackupVO) => {
  viewForm.value = { ...initFormData };
  viewBackupPersonName.value = '';
  const res = await getProDataBackup(row.id);
  Object.assign(viewForm.value, res.data);
  // 回显备份人员名称
  if (res.data.backupName) {
    viewBackupPersonName.value = res.data.backupName;
  }
  // 如果有项目ID，通过项目ID单独请求项目信息确保正确回显
  if (res.data.proId) {
    try {
      const projectRes = await listProInfoForQuery({ id: res.data.proId, pageNum: 1, pageSize: 1, auditStatus: '3' });
      if (projectRes.rows && projectRes.rows.length > 0) {
        const project = projectRes.rows[0];
        viewForm.value.proName = project.proName;
        viewForm.value.proPresidentsName = project.proPresidentsName || '';
        viewForm.value.proLeadersName = project.proLeadersName || '';
      }
    } catch (error) {
      console.error('获取项目信息失败:', error);
      // 如果单独请求失败，使用原有的项目名称
      if (res.data.proName) {
        viewForm.value.proName = res.data.proName;
      }
    }
  }
  viewDialog.visible = true;
  viewDialog.title = "查看数据备份记录详情";
}

/** 提交按钮 */
const submitForm = () => {
  proDataBackupFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateProDataBackup(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addProDataBackup(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProDataBackupVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除数据备份记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delProDataBackup(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('pro/backup/export', {
    ...queryParams.value
  }, `project_data_backup_${new Date().getTime()}.xlsx`)
}

 

// 搜索用UserSelector处理方法
const handleSearchPresidentConfirm = (data: any) => {
  if (data.users && data.users.length > 0) {
    const user = data.users[0];
    selectedSearchPresident.value = user;
    queryParams.value.proPresidentId = user.userId;
  }
  showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  queryParams.value.proPresidentId = undefined;
};

const handleSearchLeaderConfirm = (data: any) => {
  if (data.users && data.users.length > 0) {
    const user = data.users[0];
    selectedSearchLeader.value = user;
    queryParams.value.proLeaderId = user.userId;
  }
  showSearchLeaderSelector.value = false;
};

const handleSearchLeaderCancel = () => {
  showSearchLeaderSelector.value = false;
};

const clearSearchLeader = () => {
  selectedSearchLeader.value = null;
  queryParams.value.proLeaderId = undefined;
};

const handleSearchBackupPersonConfirm = (data: any) => {
  if (data.users && data.users.length > 0) {
    const user = data.users[0];
    selectedSearchBackupPerson.value = user;
    queryParams.value.backupBy = user.userId;
  }
  showSearchBackupPersonSelector.value = false;
};

const handleSearchBackupPersonCancel = () => {
  showSearchBackupPersonSelector.value = false;
};

const clearSearchBackupPerson = () => {
  selectedSearchBackupPerson.value = null;
  queryParams.value.backupBy = undefined;
};

// 审核流程相关
const approvalFlowVisible = ref(false);
const currentBackupForApproval = ref<any>(null);
const businessType = ref('DATA-BACKUP-AUDIT');

/**
 * 提交数据备份审核
 */
const handleSubmitAudit = (row: any) => {
  if (!row.id) {
    ElMessage.error('备份记录ID不能为空');
    return;
  }

  currentBackupForApproval.value = {
    id: row.id,
    proName: row.proName || '数据备份'
  };
  approvalFlowVisible.value = true;
};

/**
 * 审核流程确认回调
 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('审核流程提交成功');
    approvalFlowVisible.value = false;
    currentBackupForApproval.value = null;
    // 刷新列表
    await getList();
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/**
 * 审核流程取消回调
 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentBackupForApproval.value = null;
};

onMounted(() => {
  getList();
  getProjectList(); // 初始化项目列表
});

onUnmounted(() => {
  if (searchProjects.timer) {
    clearTimeout(searchProjects.timer);
  }
});
</script>

<style scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-fixed {
  margin-top: 8px;
}
</style>
